var e, a, t = getApp();
Page({
    data: {
        huiyuan:0,
        tokenValue: null,
        user:[],
        userInfo: {},
        is_first_action: !0,
        userService: [ {
            name: "我的砍价",
            icon: "daojianfu",
            link: "../bargain/order/index",
            color: "#FF0C4B"
        }, {
            name: "我的拼团",
            icon: "shehuituanti",
            link: "../group/order/index",
            color: "#FFB80C"
        }, {
            name: "我的分享",
            icon: "tableshare",
            link: "../user/speak",
            color: "#00B9FD"
        }, {
            name: "增值发票",
            icon: "fapiaoguanli",
            link: "../invoice/create",
            color: "#FD4100"
        }, {
            name: "收货地址",
            icon: "dizhi",
            link: "../address/index",
            color: "#7ACF00"
        } ]
    },
    onShow: function() {
        /* wx.getSetting({
            success: (result) => {
                console.log(result);
            },
            fail: () => {},
            complete: () => {}
        });
           */
        const value = wx.getStorageSync('token')
        var fromid = wx.getStorageSync("from_id");
        if(value){
            this.setData({
                tokenValue: value
            })
        }
        var e = this;
        e.setData({
            marginTop:getApp().globalData.navbarHeight + getApp().globalData.statusBarHeight
        })
        wx.setStorageSync("flowcheckout", {
            from: "user"
        }),
        a = wx.getStorageSync("goodshistory");
        var o = wx.getStorageSync("goodsNum");
        e.setData({
            goodsNum: o
        }),
        t.getUserInfo(function(a) {
            e.setData({
                userInfo: a
            });
        
        }),
        e.setData({
            is_first_action: !0
        }),
        this.setData({
            recommend: "",
            orderNum: ""
        });
        if(value){
            e.user(1);
          
            getApp().setCartNum(); 
        }
       
    },
    
    onReady: function () {
        //获得dialog组件
        this.dialog = this.selectComponent("#bind");
        console.log(this.dialog);
    },

    showDialog: function () {
        this.dialog.showDialog();
    },

    //取消事件
    _cancelEvent: function () {
        console.log('你点击了取消');
        this.dialog.hideDialog();
    },
    //确认事件
    _confirmEvent: function () {
        console.log('你点击了确定');
        this.dialog.hideDialog();
    },
    user: function(showd) {
        var e = this, o = wx.getStorageSync("token");
        console.log(o);
        if(!o){
            return;
        }
        var that = this;
        wx.request({
            url: t.apiUrl("user"),
            data: {
                per_page: "10",
                page: "1",
                list: a
            },
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": o
            },
            method: "POST",
            success: function(a) {
                e.setData({
                    recommend: a.data.data.best_goods,
                    orderNum: a.data.data.order,
                    user: a.data.data,
                    hidden: !0
                });
                console.log(showd);
               
                e.setData({
                    huiyuan:a.data.data.userInfo.user_rank
                })
                // e.setData({
                //     huiyuan:0
                // })
                console.log('用户会员',a.data.data.userInfo.user_rank)
                if(showd == 1 && a.data.data.userInfo.bindPhone == ''){ // && a.data.data.userInfo.reg_time > 1599044621
                    console.log(123);
                    wx.checkSession({
                        success: (result) => {
                            console.log(result);
                            that.showDialog();
                        },
                        fail: () => {},
                        complete: () => {}
                    });       
                    
                }
                //e.asyncCartGoods()
            }
        });
    },
    bindGetUserInfo: function (e) {
        if(this.data.tokenValue){
            return
        }else{
            if (e.detail.userInfo) {
                var fromid = wx.getStorageSync("from_id");
                var teamid = wx.getStorageSync("teamid");
                
                console.log("点击了同意授权");
                this.setData({
                    userInfo: e.detail.userInfo
                })
                var t = this;
                wx.login({
                    success: function (o) {
                        var n = o.code;
                        wx.getUserInfo({
                            withCredentials: !0,
                            lang: "zh_CN",
                            success: function (o) {
                                o.userInfo.code = n
                                o.userInfo.fromid = fromid
                                o.userInfo.teamid = teamid
                                t.doLogin(n, o)
                            },
                        });
                    }
                });
            }
        }
    },
    doLogin: function (e, t) {
        var o = this;
        e ? wx.request({
            url: o.apiUrl("user/login"),
            method: "POST",
            data: {
                userinfo: t,
                code: e
            },
            success: function (e) {
                wx.removeStorageSync('token') ;
                wx.removeStorageSync('openid') ;
                wx.setStorageSync("token",e.data.data.token), 
                wx.setStorageSync("openid",e.data.data.openid);
                console.log(e.data.data.token,wx.getStorageSync("token"),e.data.data.openid,wx.getStorageSync("openid"));
                o.user()
                getApp().setCartNum();   
                //o.bindPhone(e);  
            }
        }) : console.log("获取用户登录态失败！" + res.errMsg);
    },
    apiUrl: function (e) {
        return "https://piwx.llmaicai.com/" + e;
    },
    invoiceNav: function(a) {
        var o = this;
        e = wx.getStorageSync("token"), 1 == o.data.is_first_action && (o.setData({
            is_first_action: !1
        }), wx.request({
            url: t.apiUrl("user/invoice/detail"),
            method: "POST",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": e
            },
            success: function(e) {
                0 != e.data.data ? wx.navigateTo({
                    url: "../invoice/detail"
                }) : wx.navigateTo({
                    url: "../invoice/create"
                }), o.setData({
                    invoices: e.data.data
                });
            }
        }));
    },
    psshijian:function(){
        wx.showToast({
            title: '07:00-22:00',
            icon: 'success',
            duration: 2000
          })
    },
    navgateToUrl:function(e){
        var token = wx.getStorageSync("token");
        if(!token){
            wx.showToast({
                title: '未登录',
                icon: 'none'
            });
         return;     
        }
        var url =e.currentTarget.dataset.url;
        wx.navigateTo({
            url: url,
            success: (result) => {
                
            },
            fail: () => {},
            complete: () => {}
        });
          
    },
    userAddress: function(e) {
        wx.navigateTo({
            url: "../address/index"
        });
    },
    onPullDownRefresh: function() {
        var e = this;
        wx.showNavigationBarLoading(), e.user(), setTimeout(function() {
            wx.hideNavigationBarLoading(), wx.stopPullDownRefresh();
        }, 1500);
    },
    onShareAppMessage: function() {
        return {
            title: "花少钱,吃好菜,让您满意的乐乐买菜",
            desc: "乐乐买菜是一个围绕着老百姓餐桌的生鲜电商结合先上线下平台",
            path: "/pages/user/user"
        };
    },
    calling: function () {
        wx.makePhoneCall({
          phoneNumber: '400-688-7977',
          success: function () {
            console.log("拨打电话成功！")
          },
          fail: function () {
            console.log("拨打电话失败！")
          }
        })
    },
    asyncCartGoods:function(){
        var token = wx.getStorageSync("token");
        let goods = this.data.recommend;
        var that = this;
            
        wx.request({
            url: getApp().apiUrl("index/getCartGoods"),
            method: "post",
            header: {
            "Content-Type": "application/json",
            "X-ECTouch-Authorization": token
            },
            success: function (t) {
            if(t.data.data.length == undefined){
                t.data.data = [];
            }
            let cartGoods = t.data.data;
            goods.forEach((item,key)=>{
                goods[key].cart_num = 0;
                cartGoods.forEach((val)=>{
                if(val.goods_id == item.goods_id){
                    goods[key].cart_num = val.goods_number
                }

                })

            })
            
            that.setData({
                recommend:goods
            });
            
            }
        });
    
    },
    onOpenContact: function () {
        t.QDTracker.click();
    },
    goodsCheckout: function (t) {
        let type = t.currentTarget.dataset.type;
        let index = t.currentTarget.dataset.index;
        let goods = this.data.recommend;
        let that = this;
        if(type == 'jia'){
  
          getApp().goodsCheckout_v2(t).then((res) => {
              if(res.data.data.code == -1){
                wx.showModal({
                  title: '提示',
                  content: res.data.data.msg,
                  showCancel:false,
                })
              }else{
                goods[index].cart_num ++;
                that.setData({
                    recommend:goods
                });
              }
            })
        }else{
          goods[index].cart_num --;
          if(goods[index].cart_num > 0){
            getApp().goodsCartUpdate(t,goods[index].cart_num)
          }else{
            getApp().goodsCartDelete(t)
  
          }
          that.setData({
            recommend:goods
          });
        }
    },
    getPhoneNumber:function(e){  
        var that = this;
        wx.checkSession({
            success: (result) => {
                that.bindPhone(e);
            },
            fail: () => {
                wx.login({
                    timeout:10000,
                    success: (result) => {
                        var n = result.code;
                        wx.getUserInfo({
                            withCredentials: !0,
                            lang: "zh_CN",
                            success: function (o) {
                                o.userInfo.code = n
                                that.doLogin(n, o)
                                //that.bindPhone(e);
                            },
                        });
                    },
                    fail: () => {},
                    complete: () => {}
                });
                  
            },
            complete: () => {}
        });
        
    },
    bindPhone:function(e){
        console.log(e)
        var that = this;
        if(this.data.user.userInfo.bindPhone != ''){
            return false;
        }
        var token = wx.getStorageSync("token");
        if(e.type == 'run'){
            var iv =  e.detail.detail.iv;
            var encryptedData =  e.detail.detail.encryptedData;
        }else{
            var iv =  e.detail.iv;
            var encryptedData =  e.detail.encryptedData;
        }
        wx.request({
            url: getApp().apiUrl("user/bindPhone"),
            method: "post",
            header: {
            "Content-Type": "application/json",
            "X-ECTouch-Authorization": token
            },
            data: {
                iv: iv,
                encryptedData:encryptedData
            },
            success: function (t) {
                console.log(t);
                if(t.data.data.error == 0){ 
                    that.setData({
                        "user.userInfo.bindPhone":t.data.data.phone
                    });
                    that.dialog.hideDialog();
                    wx.showToast({
                        title: '绑定成功',
                        icon: 'none',
                        image: '',
                        duration: 1500,
                        mask: false,
                        success: (result) => {
                            
                        },
                        fail: () => {},
                        complete: () => {}
                    });   
                }
            }
        });
    }
});